<template>
  <view class="relayTheMessage" :style="DynamicHeight">
    <up-navbar title="选择联系人" :autoBack="false" placeholder @leftClick="leftClick"></up-navbar>
    <view>
      <!-- 输入框 -->
      <view>
        <up-input placeholder="请输入名称" border="surround" v-model="keyword" @change="searchchange" shape="circle"
          :customStyle="{
            width: '90vw', margin: '0  auto'
          }"></up-input>
      </view>

      <view>
        <up-tabs :current="tabsindex" :list="tabslist" @click="tabsclick"></up-tabs>
      </view>
      <view style="padding: 3px 10px;" :style="tabsDynamicHeight">
        <view>
          <scroll-view :scroll-top="scrollTop" :refresher-background="'transparent'" :style="tabsDynamicHeight"
            class="Contact-menu" scroll-y="true" :refresher-enabled="true" :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresh" @scrolltolower="loadMore">

            <view v-for="(item) in RecentChatList" :key="item.id" @click="ForwardingTime(item)">
              <!-- 联系人列表 -->
              <template v-if="tabsindex == 0">
                <view class="list-item">
                  <view class="img" style="width: 82rpx; height: 82rpx;">
                    <up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
                      <template #error>
                        <text>{{ showUserName(item.username) }}</text>
                      </template>
                    </up-image>
                  </view>
                  <view>
                    {{ item.username }} {{ item.username_en }}
                  </view>
                </view>
              </template>

              <!-- 群组列表 -->
              <template v-else>
                <view class="list-item" v-if="!item.group_id">
                  <view class="img" style="width: 82rpx; height: 82rpx;">
                    <up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
                      <template #error>
                        <text>{{ showUserName(item.username) }}</text>
                      </template>
                    </up-image>
                  </view>
                  <view>
                    {{ item.username }}
                  </view>
                </view>

                <view class="list-item" v-else>
                  <group-avatar :chat="item" :groupname="item.group_name"></group-avatar>
                  <view style="margin-left: 10px;">
                    {{ item.username || item.group_name }}
                  </view>
                </view>
              </template>
            </view>

            <!-- 加载中提示 -->
            <view v-if="loading" class="loading-text">加载中...</view>

            <!-- 没有更多数据提示 -->
            <view v-if="noMore" class="no-more-text">没有更多数据了</view>

            <view v-if="errLoading" class="no-more-text">加载数据失败请稍后重试！</view>
          </scroll-view>
        </view>
      </view>
    </view>
    <up-modal :show="memberModal" :title="memberTitle" :content="memberContent" show-cancel cancel-text="取消"
      confirm-text="确定" @confirm="memberConfirm" @cancel="memberModal = false" showCancelButton="true"
      showConfirmButton="true"></up-modal>
  </view>
</template>

<script>
import apply from "@/apis/cloud/apply.js";
import { getCurrentInstance } from 'vue'
import { useUserStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";
import GroupAvatar from '../../chat/list/GroupAvatar.vue'
export default {
  name: 'shareApprovalForm',
  components: {
    GroupAvatar,
  },
  data () {
    return {
      scrollTop: 0,
      DynamicHeight: {},
      height: 0,
      value: '',
      tabslist: [
        {
          name: '联系人',
          type: '1'
        },
        {
          name: '群组',
          type: '2'
        },

      ],
      tabsindex: 0,
      tabsDynamicHeight: {},
      keyword: '', // 搜索关键字
      userInfo: {}, // 用户信息
      imInfo: {},
      originMessageList: [], // 原始消息列表
      memberModal: false,
      memberTitle: '',
      memberContent: '',
      RecentChatList: [],
      timer: null, // 用来做防抖
      pageSize: 20, // 每页数据条数
      pageNum: 1, // 默认页码
      total: 0, // 通讯录数据总条数
      isRefreshing: false, // 是否正在下拉刷新
      loading: false, // 是否正在加载中
      noMore: false, // 是否已加载全部数据
      type: '1',
      id: '',
      ForwardingValue: {},
      errLoading: false,
    }
  },
  computed: {
    ...mapStores(useUserStore),
    filteredMessageList () {
      if (!this.keyword) {
        return this.originMessageList
      }
      const kw = this.keyword.toLowerCase()
      return this.originMessageList.filter(item => {
        const name = (item.username || item.group_name || '').toLowerCase()
        return name.includes(kw)
      })
    }
  },
  onLoad (option) {
    this.id = option.id;
  },
  created () {
    // 获取APP用户信息
    this.userInfo = this.userStore.user;
    let that = this
    const instance = getCurrentInstance().proxy;
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('chaTrelayTheMessage', async function (data) {
      // 接收消息
    })

    this.height = (uni.getSystemInfoSync().windowHeight || uni.getSystemInfoSync().screenHeight) || 0

    this.DynamicHeight = {
      height: `${this.height}px`,
      overflowY: 'hidden'
    }
    // #ifdef APP-PLUS

    this.tabsDynamicHeight = {
      height: `${this.height - 169}px`,
      overflowY: 'hidden'
    }
    // #endif

    // #ifdef H5
    this.tabsDynamicHeight = {
      height: `${this.height - 132}px`,
      overflowY: 'hidden'
    }
    // #endif
    this.getList('', '1')
  },
  methods: {
    setUserImg (item) {
      return AvaterBaseUrl + (item.friend_phone || item.phone) + '.jpg'
    },
    // tabs选择
    tabsclick (e) {
      this.pageNum = 1;
      this.total = 0;
      this.noMore = false;
      this.loading = false;
      this.RecentChatList = [];
      this.tabsindex = e.index;
      this.type = e.type;
      this.getList(this.keyword, e.type);
      this.scrollTop = 1;
      this.$nextTick(() => {
        this.scrollTop = 0;
      });
    },
    // 输入框
    searchchange (e) {
      this.keyword = e;
      this.RecentChatList = [];
      this.pageNum = 1;
      this.noMore = false;
      this.total = 0
      // 防抖处理
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.getList(this.keyword);
      }, 200);
    },
    // 通讯录选中
    ForwardingTime (value) {
      console.log('value', value);
      this.ForwardingValue = value
      this.memberTitle = `分享给${value.group_name || value.username}吗`
      this.memberModal = true
    },
    async memberConfirm () {
      uni.showLoading({
        title: '加载中'
      });

      let data = {
        ...this.ForwardingValue,
        key: `${this.type}-${(this.ForwardingValue.id || this.ForwardingValue.group_id)}`,
        id: `${(this.ForwardingValue.id || this.ForwardingValue.group_id)}`,
        type: this.type
      }
      try {
        let res = await apply.ApplyshareApply({
          id: this.id,
          send: JSON.stringify([data])
        })
        uni.hideLoading();
        if (res.status == 1) {
          uni.showToast({
            title: res.msg,
            icon: 'success'
          });
          this.memberModal = false
          setTimeout(() => {
            uni.navigateBack()
          }, 500);
        } else {
          uni.showToast({
            title: res.msg || '分享失败',
            icon: 'error'
          });
          this.memberModal = false
        }
      } catch (error) {
        uni.showToast({
          title: '分享失败',
          icon: 'error'
        });
        uni.hideLoading();
        this.memberModal = false
      }
    },
    // 
    onRefresh () {
      this.isRefreshing = true; // 开始刷新
      this.RecentChatList = [];
      this.pageNum = 1;
      this.noMore = false;
      return this.getList(this.keyword, this.type);
    },
    // 
    loadMore () {
      if (this.loading || this.noMore) return;
      this.pageNum++;
      this.getList(this.keyword, this.type);
    },

    // 获取数据
    async getList (value = '', type = '1') {
      if (this.loading) {
        // 隐藏加载框
        uni.hideLoading();
        return
      }
      this.loading = true;

      if (this.pageNum === 1) {
        this.noMore = false;
      }
      try {
        uni.showLoading({
          title: '加载中'
        });

        const data = {
          keywords: value,
          page: this.pageNum,
          row: this.pageSize,
          type: type
        }

        const res = await apply.ApplygetRecentChat(data);

        if (res.status === 1) {
          this.RecentChatList = this.pageNum === 1 ? res.data : [...this.RecentChatList, ...res.data];
          this.total = res.total;
          if (this.RecentChatList.length >= this.total) {
            this.noMore = true;
          }
          this.isRefreshing = false;
          this.loading = false;
          uni.hideLoading();
        } else {
          this.errLoading = true
          this.loading = false;
          this.noMore = false;
          this.isRefreshing = false;
          uni.hideLoading();
        }
      } catch (error) {
        this.errLoading = true
        uni.hideLoading();
        this.loading = false;
        this.isRefreshing = false;
        console.error('请求失败', error);
        uni.showToast({
          title: '请求失败',
          icon: 'error'
        });
      }
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    // 返回
    leftClick () {
      uni.navigateBack()
    }
  }
}
</script>


<style lang="scss" scoped>
.relayTheMessage {
  width: 100%;
  background-color: #ffffff;

  // 通讯录
  .apply-menu {
    overflow-y: auto;

    .list-item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 20rpx;
      border-bottom: 0.5px solid #ddd;

      .check {
        margin-right: 10rpx;
      }

      .img {
        margin-right: 24rpx;

        text {
          display: inline-block;
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
          color: #fff;
          font-size: 26rpx !important;
          text-align: center;
          line-height: 82rpx;
          background-color: #3D85FC;
        }
      }

      .del {
        position: absolute;
        right: 10rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }

  }

  // 最近聊天
  .Contact-menu {
    overflow-y: auto;

    .list-item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 20rpx;
      border-bottom: 0.5px solid #ddd;

      .check {
        margin-right: 10rpx;
      }

      .img {
        margin-right: 24rpx;

        text {
          display: inline-block;
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
          color: #fff;
          font-size: 26rpx;
          text-align: center;
          line-height: 80rpx;
          background-color: #3D85FC;
        }
      }
    }

  }





  /* 加载中和无更多数据提示 */
  .loading-text,
  .no-more-text {
    margin-top: 20rpx;
    text-align: center;
    padding: 20rpx;
    color: #999;
    font-size: 28rpx;
  }


}
</style>
